package com.ipartek.formacion.primerwebapp.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MiPrimerServletP1
 */
public class MiPrimerServletP1 extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MiPrimerServletP1() {
        super();
        // TODO Auto-generated constructor stub
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println ("Estoy accediendo por GET");
		
		PrintWriter out;
		String title = "Simple Servlet Output";
		// primero selecciona el tipo de contenidos y otros campos de cabecera de la respuesta
		response.setContentType("text/html");
		// Luego escribe los datos de la respuesta
		out = response.getWriter();
		out.println(title);
		out.println("</TITLE></HEAD><BODY>");
		out.println("<H1>" + title + "</H1>");
		out.println("<P>This is output from SimpleServlet.");
		out.println("</BODY></HTML>");
		out.close(); 
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println ("Estoy accediendo por POST");
		
		PrintWriter out;
		response.setContentType("text/html");
		out = response.getWriter();
	
		String title = "SALIDA DE DATOS";
		
		out.println ("<H1> Hemos lleagdo con el Boton: "+ request.getParameter("opcion") + "</H1>");
		
		if (request.getParameter("opcion").equals("Opcion1")){
			
			/*out.println("</TITLE></HEAD><BODY>");
			out.println("<H1>" + title + "</H1>");			
			out.println ("<H1> El usuario es: "+ request.getParameter("uname") + "</H1>");
			out.println ("<H1> La Password es: "+ request.getParameter("pass") + "</H1>");
			
			out.println("</BODY></HTML>");
			out.close();*/
			/*response.sendRedirect("opcion1.jsp");*/
			request.getSession().setAttribute("servletMsg", request.getParameter("uname")); 
			response.sendRedirect("opcion1.jsp");
		};
		if (request.getParameter("opcion").equals("Opcion2")){
			out.println("</TITLE></HEAD><BODY>");
			out.println("<H1>" + title + "</H1>");
			out.println ("<H1> El usuario es: "+ request.getParameter("uname") + "</H1>");
			out.println ("<H1> La Password es: "+ request.getParameter("pass") + "</H1>");
			
			out.println("</BODY></HTML>");
			out.close();
		};
	}

}
